package com.wuhaha.a1911_demo.ui.Login;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wuhaha.a1911_demo.R;
import com.wuhaha.a1911_demo.model.UserMessage;
import com.wuhaha.libnetwork2.network.ApiResponse;
import com.wuhaha.libnetwork2.network.ApiServices;
import com.wuhaha.libnetwork2.network.JsonCallback;

import org.json.JSONException;
import org.json.JSONObject;

public
/**
 * Create date: On 2022/8/22
 */
class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private View actionClose;
    private View actionLogin;
    private Tencent ten;
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_login);

        actionClose = findViewById(R.id.action_close);
        actionLogin = findViewById(R.id.action_login);

        actionClose.setOnClickListener(this);
        actionLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.action_close){
            finish();
        }else if (v.getId() == R.id.action_login){
            login();
        }
    }

    //QQ快捷登录的api
    private void login() {
        if (ten == null){
            ten = Tencent.createInstance("101794421",getApplicationContext());
        }
        ten.login(this,"all",loginListener);
    }

    IUiListener loginListener = new IUiListener(){

        @Override
        public void onComplete(Object o) {
            JSONObject response = (JSONObject) o;
            try{
                String openid = response.getString("openid");
                String access_token = response.getString("access_token");
                String expires_in = response.getString("expires_in");
                //过期时间
                long expires_time = response.getLong("expires_time");

                ten.setOpenId(openid);
                ten.setAccessToken(access_token,expires_in);
                //获取用户信息
                QQToken qqToken = ten.getQQToken();
                getUser(qqToken, expires_time, openid);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext(), "登录失败:reason" + uiError.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(), "登录取消", Toast.LENGTH_SHORT).show();
        }
    };
    //获取用户信息
    private void getUser(QQToken qqToken, long expires_time, String openid) {
        UserInfo userInfo = new UserInfo(getApplicationContext(), qqToken);
        userInfo.getUserInfo(new IUiListener(){

            @Override
            public void onComplete(Object o) {
                JSONObject response = (JSONObject) o;
                try {
                    String nickname = response.getString("nickname");
                    String figureurl_2 = response.getString("figureurl_2");
                    //上传用户信息到服务器
                    saves(nickname, figureurl_2, openid, expires_time);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {
                Toast.makeText(getApplicationContext(), "登录失败:reason" + uiError.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "登录取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saves(String nickname, String figureurl_2, String openid, long expires_time) {
        ApiServices.get("/user/insert")
                .addParam("name", nickname)
                .addParam("avatar", figureurl_2)
                .addParam("qqOpenId", openid)
                .addParam("expires_time", expires_time)
                .execute(new JsonCallback<UserMessage>() {
                    @Override
                    public void onSuccess(ApiResponse<UserMessage> response) {
                        //持续化存储用户信息
                        if (response.body != null) {
                            UserManager.get().saves(response.body);
                            finish();
                        } else {
                            //抛到主线程
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "登陆失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(ApiResponse<UserMessage> response) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "登陆失败,msg:" + response.message, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }
    }
}
